<template>
  <div class="login-page mx-auto p-3 w-330">
    <validate-form @form-submit="onFormSubmit">

      <div class="mb-3">
        <label for="formGroupExampleInput" class="form-label">邮箱地址</label>
        <!--地址验证-->
        <!--v-model 是父传子 传值的作用-->
        <vaildate-input 
        placeholder="请输入账号" 
        v-model="emailVal" 
        :rules="emailRules" 
        @value="emailValue">
        </vaildate-input>
      </div>

      <!--密码验证-->
      <div class="mb-3">
        <label for="formGroupExampleInput2" class="form-label">密码</label>
        <vaildate-input 
        placeholder="请输入密码" 
        v-model="passwordVal" :rules="passwordRules" @value="passwordValue">
        </vaildate-input>
      </div>
      <!-- 插值，插入ValidateForm-->
      <template #submit>
        <span type="submit" class="btn btn-danger">登录</span>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import ValidateForm from "@/components/ValidateForm.vue";
import VaildateInput, { RulesProp } from "@/components/VaildateInput.vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import createMessage from '@/hooks/createMessage';


export default defineComponent({
  components: {
    ValidateForm,
    VaildateInput
  },
  setup() {
    // 邮箱验证
    const emailVal = ref('111@test.com')
    //接收子传的值,实现vue3的双向绑定
    const emailValue = (val: string) => {
      // console.log(val);
      emailVal.value = val
    }
    //邮箱验证规则
    const emailRules: RulesProp = [
      //这个是邮箱的规则，应该被这个东西所约束
      { type: 'required', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的邮箱规则' }
    ]

    //密码验证
    const passwordVal = ref('111111')

    const passwordValue = (val: string) => {
      passwordVal.value = val
    }
    const passwordRules: RulesProp = [
      //这个是邮箱的规则，应该被这个东西所约束
      { type: 'required', message: '密码不能为空' }
    ]


    // 登录按钮被点击时，接收子组件的参数
    const store = useStore()
    const router = useRouter()
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        }
        store.dispatch('loginAndFecth', payload).then(() => {
          //  发送登录
          createMessage('登录成功 2秒后跳转首页', 'success')
          setTimeout(() => {
            router.push('/')
          }, 2000)
        }).catch((e) => {
          console.log(e);
        })

      }
    }

    return {
      emailRules,
      emailVal,
      emailValue,
      onFormSubmit,
      passwordVal,
      passwordValue,
      passwordRules
    }
  }
})
</script>

<style scoped>
.w-330 {
    max-width: 330px;
}
</style>